<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createUser, updateUser, type UserCreateDTO, type UserInfo } from '../../api/user'

interface Props {
  visible: boolean;
  availableRoles: Array<{value: number, label: string}>;
  isEditMode?: boolean;
  editUser?: UserInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  availableRoles: () => [],
  isEditMode: false,
  editUser: null
})

const emit = defineEmits(['update:visible', 'success', 'close'])

// 密码显示控制
const showPassword = ref(false)

// 切换密码显示状态
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 对话框可见性的计算属性，支持双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 创建用户相关
const formRef = ref<FormInstance>()
const submitting = ref(false)
const formErrors = ref<string[]>([])

// 用户表单数据
const userForm = ref<UserCreateDTO>({
  username: '',
  password: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: '',
  role: 3,
  status: 1
})

// 监听编辑用户的变化，填充表单
watch(() => props.editUser, (newVal) => {
  if (newVal && props.isEditMode) {
    // 注意：编辑模式下不需要密码
    userForm.value = {
      username: newVal.username || '',
      password: '', // 编辑时不修改密码
      nickname: newVal.nickname || '',
      phone: newVal.phone || '',
      email: newVal.email || '',
      avatar: newVal.avatar || '',
      role: newVal.role || 3,
      status: newVal.status || 1
    }
  } else {
    resetForm() // 如果不是编辑模式，重置表单
  }
}, { immediate: true })

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: !props.isEditMode, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 重置表单
const resetForm = () => {
  userForm.value = {
    username: '',
    password: '',
    nickname: '',
    phone: '',
    email: '',
    avatar: '',
    role: 3,
    status: 1
  }
  formErrors.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  dialogVisible.value = false
  emit('close')
}

// 提交用户表单
const submitUserForm = async () => {
  if (!formRef.value) return
  
  formErrors.value = []
  
  try {
    // 使用Element Plus表单验证
    await formRef.value.validate()
    
    // 开始提交
    submitting.value = true

    if (props.isEditMode && props.editUser) {
      // 编辑用户
      const updateData: Record<string, any> = { ...userForm.value }
      // 如果密码为空，删除密码字段，不发送到后端
      if (!updateData.password) {
        delete updateData.password
      }
      
      // 获取正确的用户ID（兼容大写ID或小写id）
      const userId = props.editUser.ID || props.editUser.id
      
      if (!userId) {
        throw new Error('无效的用户ID')
      }
      
      await updateUser(userId, updateData)
      ElMessage.success('更新用户成功')
    } else {
      // 创建新用户
      await createUser(userForm.value)
      ElMessage.success('创建用户成功')
    }
    
    handleClose()
    emit('success')
  } catch (error: any) {
    // 表单验证失败不需处理，接口错误已由拦截器处理
    if (!formErrors.value.length && !(error instanceof Error)) {
      formErrors.value.push(props.isEditMode ? '更新用户失败，请重试' : '创建用户失败，请重试')
    } else if (error instanceof Error) {
      formErrors.value.push(error.message)
    }
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="520px"
    destroy-on-close
    class="user-dialog"
    :close-on-click-modal="false"
    :show-close="false"
    @closed="handleClose"
  >
    <div class="dialog-content">
      <div class="dialog-header">
        <div class="header-left">
          <h3>{{ isEditMode ? '编辑用户' : '创建新用户' }}</h3>
          <p>{{ isEditMode ? '修改用户信息' : '添加一个新的用户账户' }}</p>
        </div>
        <div class="header-right">
          <button class="btn-close" @click="handleClose">
            <i class="el-icon-close"></i>
          </button>
        </div>
      </div>
      
      <el-form 
        ref="formRef"
        :model="userForm" 
        :rules="rules"
        label-position="top"
      >
        <!-- 表单错误提示 -->
        <div v-if="formErrors.length > 0" class="form-errors">
          <div class="error-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="error-list">
            <p v-for="(error, index) in formErrors" :key="index" class="error-item">{{ error }}</p>
          </div>
        </div>

        <div class="form-grid">
          <!-- 姓名和昵称 -->
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">用户名</span>
              <span class="label-required">*</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-user"></i>
              <input 
                v-model="userForm.username" 
                class="form-input" 
                placeholder="请输入用户名"
                :disabled="isEditMode"
              />
            </div>
            <span class="input-tip">3-20个字符，可包含字母、数字</span>
          </div>
          
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">昵称</span>
              <span class="label-required">*</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-user"></i>
              <input 
                v-model="userForm.nickname" 
                class="form-input" 
                placeholder="请输入昵称"
              />
            </div>
          </div>
          
          <!-- 密码 -->
          <div class="form-block full-width">
            <label class="form-label">
              <span class="label-text">密码</span>
              <span v-if="!isEditMode" class="label-required">*</span>
              <span v-else class="label-optional">(留空表示不修改)</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-lock"></i>
              <input 
                v-model="userForm.password" 
                :type="showPassword ? 'text' : 'password'" 
                class="form-input" 
                :placeholder="isEditMode ? '留空表示不修改密码' : '请输入密码'"
              />
              <button 
                class="input-action" 
                title="显示/隐藏密码"
                type="button"
                @click="togglePasswordVisibility"
              >
                <i :class="showPassword ? 'el-icon-view' : 'el-icon-hide'"></i>
              </button>
            </div>
            <span v-if="!isEditMode" class="input-tip">至少6个字符</span>
          </div>
          
          <!-- 联系信息 -->
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">手机号</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-mobile-phone"></i>
              <input 
                v-model="userForm.phone" 
                class="form-input" 
                placeholder="请输入手机号"
              />
            </div>
          </div>
          
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">邮箱</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-message"></i>
              <input 
                v-model="userForm.email" 
                class="form-input" 
                placeholder="请输入邮箱"
              />
            </div>
          </div>
          
          <!-- 其他信息 -->
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">头像URL</span>
            </label>
            <div class="input-wrapper">
              <i class="input-icon el-icon-picture"></i>
              <input 
                v-model="userForm.avatar" 
                class="form-input" 
                placeholder="请输入头像URL"
              />
            </div>
          </div>
          
          <div class="form-block">
            <label class="form-label">
              <span class="label-text">角色</span>
              <span class="label-required">*</span>
            </label>
            <div class="select-wrapper">
              <select v-model="userForm.role" class="form-select">
                <option disabled value="">请选择角色</option>
                <option 
                  v-for="item in props.availableRoles" 
                  :key="item.value" 
                  :value="item.value"
                >
                  {{ item.label }}
                </option>
              </select>
              <i class="select-icon el-icon-arrow-down"></i>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    
    <div class="dialog-footer">
      <button class="btn-cancel" @click="handleClose">
        取消
      </button>
      <button 
        class="btn-submit" 
        @click="submitUserForm"
        :disabled="submitting"
      >
        <i class="el-icon-check"></i>
        {{ submitting ? '提交中...' : (isEditMode ? '保存修改' : '创建用户') }}
      </button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
/* 用户对话框样式 */
.user-dialog {
  :deep(.el-dialog) {
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.12);
    border: none;
    background: #f8fafc;
  }

  :deep(.el-dialog__header) {
    display: none;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    display: none;
  }

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px 32px;
    background: linear-gradient(135deg, #4c6ef5, #6e9fff);
    color: white;
    
    .header-left {
      h3 {
        font-size: 22px;
        font-weight: 600;
        margin: 0 0 8px 0;
      }
      
      p {
        margin: 0;
        opacity: 0.8;
        font-size: 14px;
      }
    }
    
    .btn-close {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: rotate(90deg);
      }
      
      i {
        font-size: 18px;
      }
    }
  }

  .dialog-content {
    padding: 0;
  }
  
  .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    padding: 32px;
    background: white;
    
    .full-width {
      grid-column: span 2;
    }
  }

  .form-errors {
    margin: 0 32px 20px;
    padding: 12px 16px;
    background: #fff5f5;
    border-radius: 12px;
    display: flex;
    gap: 12px;
    border-left: 4px solid #f56c6c;
    
    .error-icon {
      color: #f56c6c;
      font-size: 22px;
      flex-shrink: 0;
    }
    
    .error-list {
      flex: 1;
      
      .error-item {
        margin: 4px 0;
        font-size: 13px;
        color: #ff4d4f;
        line-height: 1.5;
      }
    }
  }
  
  .form-block {
    display: flex;
    flex-direction: column;
  }
  
  .form-label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
    
    .label-required {
      color: #f43f5e;
      margin-left: 4px;
    }
  }
  
  .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: #f1f5f9;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;
    border: 2px solid transparent;
    
    &:hover {
      background: #f8fafc;
    }
    
    &:focus-within {
      background: white;
      border-color: #4c6ef5;
      box-shadow: 0 0 0 4px rgba(76, 110, 245, 0.1);
    }
  }
  
  .input-icon {
    position: absolute;
    left: 14px;
    color: #94a3b8;
    font-size: 16px;
  }
  
  .form-input {
    border: none;
    background: transparent;
    height: 42px;
    padding: 0 16px 0 40px;
    font-size: 14px;
    width: 100%;
    color: #334155;
    
    &:focus {
      outline: none;
    }
    
    &::placeholder {
      color: #94a3b8;
    }
  }
  
  .input-action {
    background: none;
    border: none;
    color: #94a3b8;
    padding: 0 14px;
    cursor: pointer;
    
    &:hover {
      color: #4c6ef5;
    }
    
    i {
      font-size: 16px;
    }
  }
  
  .input-tip {
    font-size: 12px;
    color: #94a3b8;
    margin-top: 6px;
  }
  
  .select-wrapper {
    position: relative;
    background: #f1f5f9;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;
    border: 2px solid transparent;
    
    &:hover {
      background: #f8fafc;
    }
    
    &:focus-within {
      background: white;
      border-color: #4c6ef5;
      box-shadow: 0 0 0 4px rgba(76, 110, 245, 0.1);
    }
  }
  
  .form-select {
    appearance: none;
    border: none;
    background: transparent;
    height: 42px;
    padding: 0 16px;
    font-size: 14px;
    width: 100%;
    color: #334155;
    cursor: pointer;
    
    &:focus {
      outline: none;
    }
  }
  
  .select-icon {
    position: absolute;
    right: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    pointer-events: none;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 24px 32px;
    background: white;
    border-top: 1px solid #f1f5f9;
  }
  
  .btn-cancel {
    height: 42px;
    padding: 0 24px;
    border-radius: 12px;
    border: 2px solid #e2e8f0;
    background: white;
    color: #64748b;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      border-color: #cbd5e1;
      color: #475569;
    }
  }
  
  .btn-submit {
    height: 42px;
    padding: 0 24px;
    border-radius: 12px;
    border: none;
    background: linear-gradient(135deg, #4c6ef5, #6e9fff);
    color: white;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    
    i {
      margin-right: 6px;
      font-size: 14px;
    }
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(76, 110, 245, 0.25);
    }
    
    &:active {
      transform: translateY(0);
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }
  }
}

/* 添加一个新的label样式 */
.label-optional {
  color: #94a3b8;
  margin-left: 4px;
  font-size: 12px;
  font-weight: normal;
}
</style> 